package cc.beup.common.util;

import cc.beup.common.constant.PlatformResponseCodeEnum;
import cc.beup.common.exception.PlatFormBizException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Byron Bai
 * @Date: 2021/4/18 20:13
 * @Description:
 */
public class QRCodeUtil {

    private QRCodeUtil() {
    }

    /**
     * @param content 二维码内容
     * @param width   宽度
     * @param height  高度
     * @Author: Byron Bai
     * @Date: 2021/4/18 20:13
     */
    public static BufferedImage getQRCodeBuffer(String content, Integer width, Integer height) {
        //生成二维码
        MultiFormatWriter mfw = new MultiFormatWriter();
        BitMatrix bitMatrix;
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 0);
        try {
            bitMatrix = mfw.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
            throw new PlatFormBizException(PlatformResponseCodeEnum.SYS_ERROR, "二维码生成失败");
        }
        int bitWidth = bitMatrix.getWidth();
        int bitHeight = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(bitWidth, bitHeight, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitWidth; x++) {
            for (int y = 0; y < bitHeight; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    /**
     * 将BufferedImage转换为InputStream
     *
     * @Author: Byron Bai
     * @Date: 2021/4/18 16:15
     */
    public static InputStream bufferedImageToInputStream(BufferedImage image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            throw new PlatFormBizException(PlatformResponseCodeEnum.SYS_ERROR, "图片转流异常");
        }
    }
}
